package cn.fr.util;

import cn.fr.config.ConfConstConfig;
import cn.fr.entity.LoginInfo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 生产任务到队列
 */
//@Component
public class ProductTaskToQueue implements Runnable{
    private static Logger logger = LoggerFactory.getLogger("PROJECT_LOGGER");
    private RestTemplate restTemplate =new RestTemplate();
//    private ConfConstConfig confConstConfig;
    private final LinkedBlockingQueue queue;
    private final int queueCapacity ;
    private  final ReentrantLock lock;
    private  final Condition notFull ;
    private  final Condition notEmpty;

    public ProductTaskToQueue(LinkedBlockingQueue queue, int queueCapacity, ReentrantLock lock, Condition notFull, Condition notEmpty) {
        this.queue = queue;
        this.queueCapacity = queueCapacity;
        this.lock = lock;
        this.notFull = notFull;
        this.notEmpty = notEmpty;
    }


    @Override
    public void run() {
        logger.info("生产者线程开始run");
//        while (true){
            product();
//        }
    }


    private void product(){
        //获取一个随机数生成器
        ThreadLocalRandom random=ThreadLocalRandom.current();
        Long id = random.nextLong(10000);//在0~10000(包含0，不包含10000)之间的随机数
        try {
            logger.info("生产者线程要获取锁");
            lock.lock();
            logger.info("生产者线程已获取锁");
            try{
                //如果队列满了，则等待
                while (queue.size() == queueCapacity) {
                    logger.info("生产者线程调用await");
                    notEmpty.await();
                }
               List<String> resLists =getPicById(id);
                //添加元素到队列
                for (int i=0;i<resLists.size();i++) {
                    while (queue.size() == queueCapacity){
                        System.out.println("容器已经满了，等待消费者消费");
                        notEmpty.await();
                    }
                    queue.add(resLists.get(i));
                    //唤醒消费线程
                    notFull.signalAll();
                }

            }catch (Exception e) {
                e.printStackTrace();
            } finally {//释放锁
                lock.unlock();

            }

        }catch (Exception e){
            e.printStackTrace();
        }

    }

    private List getPicById(Long id) throws InterruptedException {
        HashMap params = new HashMap<>();
        params.put("q", id); //
//        String url = confConstConfig.getPicturePath();
        String url = "https://api.github.com/search/users?q";
        ResponseEntity responseEntity = restTemplate.getForEntity(url+"={q}", String.class, params);
        String res = (String) responseEntity.getBody();
        JSONObject jsonObject = JSON.parseObject(res);
        JSONArray items = (JSONArray) jsonObject.get("items");
        List<LoginInfo> lists = JSON.parseObject(items.toJSONString(), new TypeReference<List<LoginInfo>>() {});
        List<String> resLists = new ArrayList<String>();
        for (int i =0 ;i< lists.size();i++) {
            logger.info(lists.get(i).getAvatar_url());
            resLists.add(lists.get(i).getAvatar_url());
        }
        return resLists;
    }

}
